<template>
	<view class="content">
		<u-navbar title="审批配置" class="navbar" :fixed="false" leftIconColor="#fff" :safeAreaInsetTop="true"
			:autoBack="true">
		</u-navbar>


		<!-- 审批配置 -->
		<view class="fd-nav-content" :style="{height: `calc(${scollViewHeight}px)`,top: positionTop +'px'}">
			<section class="dingflow-design">
				<view class="zoom">
					<view :class="'zoom-out'+ (nowVal==50?' disabled':'')" @click="zoomSize(1)"></view>
					<text>{{nowVal}}%</text>
					<view :class="'zoom-in'+ (nowVal==300?' disabled':'')" @click="zoomSize(2)"></view>
				</view>
				<view class="box-scale" id="box-scale" style="overflow: auto;height: 100%;"
					:style="'transform: scale('+nowVal/100+'); transform-origin: 50% 0px 0px;'">

					<m-node-warp :nodeConfig.sync="nodeConfig" :flowPermission.sync="flowPermission"
						:isTried.sync="isTried" :directorMaxLevel="directorMaxLevel" :tableId="tableId"></m-node-warp>
					<view class="end-node">
						<view class="end-node-circle"></view>
						<view class="end-node-text">流程结束</view>
					</view>
				</view>
			</section>
		</view>


		<view class="x-f BottomBox" :style="{'padding-bottom':safeAreaBottom+'px','height': btnHeight + 'px'}">

			<uni-popup ref="showFlowChart" mode="center" :mask-click="false" border-radius="10px 10px 10px 10px">
				<view class="f-dc" style="width: 90vw;max-height: 80vh;min-height: 40vh;background-color: #fff;">
					<u-cell title="发起审批" style="background-color: #51d0d0;"
						:titleStyle="{color: '#fff',fontSize: '12px'}">
						<template slot="right-icon">
							<view @click="closeFlowChart">
								<u-icon name="close" color="#fff" size="16"></u-icon>
							</view>
						</template>
					</u-cell>

					<!-- <view style="flex: 1;overflow: auto;background-color: #fffbea;"> -->
					<mFlowCharts ref="flowCharts" style="flex: 1;overflow: auto;" :option="flowChartData">
					</mFlowCharts>
					<!-- </view> -->

					<view class="x-ec" style="width: 100%;height: 40px;">
						<button class="content_bottom_primary_plainBtn CommonBtnSize" @click="closeFlowChart"
							style="padding: 6px 15px !important;margin-right: 8px;">取消</button>
						<button class="content_bottom_primary_Btn CommonBtnSize" @click="submitFlowChart"
							style="padding: 6px 15px !important;margin-right: 8px;">确定</button>
					</view>

				</view>
			</uni-popup>


			<view class="BottomBox-btnBox">
				<button @click="cancelConfigBtn" class="content_bottom_primary_plainBtn CommonBtnSize">取消</button>
				<button @click="submitConfigBtn" class="content_bottom_primary_Btn CommonBtnSize">确定</button>
			</view>
		</view>


	</view>
</template>

<script>
	import mFlowCharts from '@/uni_modules/mc-ui/components/m-node-warp/compontent/m-flow-chart/m-flow-chart.vue';
	export default {
		components: {
			mFlowCharts
		},
		data() {
			return {
				positionTop: 44,
				scollViewHeight: 300,
				btnHeight: 60,
				safeAreaBottom: 0,
				isTried: false,
				tipList: [],
				tipVisible: false,
				nowVal: 100,
				BaseScreenParm: {},
				globalData: {},
				processConfig: {},
				nodeConfig: {},
				workFlowDef: {},
				flowPermission: [],
				directorMaxLevel: 0,
				dialogVisible: true,
				tableId: "",

				source: '',

				flowChartData: {},
				// #ifdef APP-PLUS
				eventChannel: null,
				// #endif
			};
		},
		onLoad(option) {
			// #ifdef APP-PLUS
			this.eventChannel = this.getOpenerEventChannel();
			// #endif
			let BaseScreenParm = uni.$m.utils.deepClone(this.$store.state.BaseScreenParm);
			console.log(BaseScreenParm);

			this.BaseScreenParm = BaseScreenParm;
			this.processConfig = BaseScreenParm.approveObj;
			this.globalData = BaseScreenParm.globalData;

			// uni.$m.utils.addZIndex(this.processConfig.nodeConfig);
			uni.$m.utils.addZIndex(this.processConfig.nodeConfig);
			this.nodeConfig = this.processConfig.nodeConfig;
			this.nodeConfig = this.processConfig.nodeConfig;
			this.flowPermission = this.processConfig.flowPermission;
			this.directorMaxLevel = this.processConfig.directorMaxLevel;
			this.workFlowDef = this.processConfig.workFlowDef
			this.tableId = this.processConfig.tableId

			this.source = option.source
		},
		watch: {
			nodeConfig: {
				handler(nVal, oVal) {

					// uni.$m.utils.addZIndex(this.processConfig.nodeConfig)
					uni.$m.utils.addZIndex(this.processConfig.nodeConfig);
					this.nodeConfig = this.processConfig.nodeConfig;
					this.flowPermission = this.processConfig.flowPermission;
					this.directorMaxLevel = this.processConfig.directorMaxLevel;
					this.workFlowDef = this.processConfig.workFlowDef;
					this.tableId = this.processConfig.tableId;

					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'nodeConfig',
						data: this.nodeConfig
					});
				},
				deep: true
			}
		},
		mounted() {
			let that = this;
			setTimeout(() => {
				that.getViewHeight();
			}, 300);
		},
		onUnload() {
			this.eventChannel.emit('cancel');
			uni.$off('gitCellCardInfo');

			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'nodeConfig',
				data: {}
			});
		},
		methods: {
			getViewHeight() { // 获取高度
				let that = this;
				let res = uni.getSystemInfoSync();

				let safeArea = res.safeAreaInsets; // 安全区域嵌入 top - bottom
				let safe = safeArea.top + safeArea.bottom
				// let windowHeight = res.windowHeight - safe; // 总高
				var windowHeight = res.windowHeight; // 总高
				var navHeight = 0;
				setTimeout(() => {
					uni.createSelectorQuery().select('.navbar').boundingClientRect(rect => {
						navHeight = rect.height;
						// let positionTop = navHeight + safeArea.top;
						that.positionTop = navHeight;


						uni.createSelectorQuery().select('.BottomBox').boundingClientRect(ret => {
							if (uni.getStorageSync('safeAreaBottom')) {
								that.safeAreaBottom = (+uni.getStorageSync('safeAreaBottom')) / 2;
							}

							let btnHeight = +ret.height + +that.safeAreaBottom;
							that.btnHeight = btnHeight;
							let nextData = windowHeight - (+navHeight + btnHeight);
							that.scollViewHeight = nextData;
						}).exec();


						// let nextData = windowHeight - (+navHeight + 60 + +safeArea.bottom);
						// console.log(nextData);

					}).exec();
				}, 300);
			},

			toReturn() {
				//window.location.href = ""
			},
			reErr(data) {
				if (data.childNode) {
					if (data.childNode.type == 1) { //审批人
						if (data.childNode.error) {
							this.tipList.push({
								name: data.childNode.nodeName,
								type: "审核人"
							})
						}
						this.reErr(data.childNode)
					} else if (data.childNode.type == 2) {
						if (data.childNode.error) {
							this.tipList.push({
								name: data.childNode.nodeName,
								type: "抄送人"
							})
						}
						this.reErr(data.childNode)
					} else if (data.childNode.type == 3) {
						this.reErr(data.childNode.childNode)
					} else if (data.childNode.type == 4) {
						this.reErr(data.childNode)
						for (var i = 0; i < data.childNode.conditionNodes.length; i++) {
							if (data.childNode.conditionNodes[i].error) {
								this.tipList.push({
									name: data.childNode.conditionNodes[i].nodeName,
									type: "条件"
								})
							}
							this.reErr(data.childNode.conditionNodes[i])
						}
					}
				} else {
					data.childNode = null
				}
			},
			saveSet() {
				this.isTried = true;
				this.tipList = [];
				this.reErr(this.nodeConfig);
				if (this.tipList.length != 0) {
					this.tipVisible = true;
					return;
				}
				this.processConfig.flowPermission = this.flowPermission;

			},
			zoomSize(type) {
				debugger;
				if (type == 1) {
					if (this.nowVal == 50) {
						return;
					}
					this.nowVal -= 10;
				} else {
					if (this.nowVal == 300) {
						return;
					}
					this.nowVal += 10;
				}
			},
			submitConfigBtn() { // 确认按钮

				this.flowChartData = uni.$m.utils.deepClone(this.processConfig);

				// 展示流程
				this.$refs['showFlowChart'].open()
			},
			cancelConfigBtn() { // 取消按钮
				uni.navigateBack();
			},
			submitFlowChart() { // 流程弹层确认按钮
				let that = this;
				uni.$m.utils.showLoading();

				let mainSql = ''
				let obj = {}
				if (that.source == 'QMS') {
					//插入主表信息
					mainSql =
						" insert into SYS_BillAPFlow(Type,BillName,APType,CreateTime,AppConfigStr,FormID) values('999',@BillName,1,getdate(),@AppConfigStr,@FormID) select @@identity as APFlowID ";

					obj = {
						BillName: that.processConfig.workFlowDef.name,
						AppConfigStr: JSON.stringify(that.processConfig),
						FormID: that.globalData.Id
					};
				} else {
					//插入主表信息
					mainSql =
						" insert into SYS_BillAPFlow(Type,BillName,APType,CreateTime,AppConfigStr,APPFormID) values('999',@BillName,1,getdate(),@AppConfigStr,@APPFormID) select @@identity as APFlowID ";

					obj = {
						BillName: that.processConfig.workFlowDef.name,
						AppConfigStr: JSON.stringify(that.processConfig),
						APPFormID: that.globalData.Id
					};
				}
				/*
				//插入主表信息
				let mainSql =
					" insert into SYS_BillAPFlow(Type,BillName,APType,CreateTime,AppConfigStr,APPFormID) values('999',@BillName,1,getdate(),@AppConfigStr,@APPFormID) select @@identity as APFlowID ";
				
				let obj = {
					BillName: that.processConfig.workFlowDef.name,
					AppConfigStr: JSON.stringify(that.processConfig),
					APPFormID: that.globalData.Id
				};
				*/
				try {

					this.post(mainSql, obj, function(retFlow) {
						var APFlowID = retFlow.ds[0].APFlowID;
						let appConfigObj = uni.$m.utils.deepClone(that.processConfig);
						let aPUserIDs = [],
							classIDs = [];
						for (var q = 0; q < appConfigObj.flowPermission.length; q++) {
							if (appConfigObj.flowPermission[q].type == 1) {
								aPUserIDs.push(appConfigObj.flowPermission[q].targetId);
							} else if (appConfigObj.flowPermission[q].type == 3) {
								classIDs.push(appConfigObj.flowPermission[q].targetId);
							}
						};


						//保存发起人
						let sql =
							'insert into SYS_BillAPFlowDe(APFlowID,APFlowNO,APUserID,RoleIDs,JobLevel,ClassIDs,SignedWay,FlowType) values(@APFlowID,@APFlowNO,@APUserID,@RoleIDs,@JobLevel,@ClassIDs,@SignedWay,@FlowType)';
						that.post(sql, {
							APFlowID: APFlowID,
							APFlowNO: '0',
							APUserID: aPUserIDs.join(','),
							RoleIDs: '',
							JobLevel: '0',
							ClassIDs: classIDs.join(','),
							SignedWay: '0',
							FlowType: '0'
						}, function() {});


						//保存各级审批及抄送人
						var saveApproveFunc = function(node, flowNo) {
							let caPUserIDs = [],
								cclassIDs = [],
								croleIDs = []
							let Joblevel = 0;
							let flowType = 0;
							let signedWay = 0;
							for (var k = 0; k < node.nodeUserList.length; k++) {
								if (node.nodeUserList[k].type == 1) {
									caPUserIDs.push(node.nodeUserList[k].targetId);
								} else if (node.nodeUserList[k].type == 3) {
									cclassIDs.push(node.nodeUserList[k].targetId);
								} else if (node.nodeUserList[k].type == 2) {
									croleIDs.push(node.nodeUserList[k].targetId);
								}
							}
							if (node.settype == 7) {
								Joblevel = node.examineEndDirectorLevel;
							}
							if (node.type == 1) {
								flowType = 0;
							} else {
								flowType = 1;
							}
							if (node.examineMode == 1) {
								signedWay = 0;
							} else {
								signedWay = 1;
							}

							that.post(sql, {
								APFlowID: APFlowID,
								APFlowNO: flowNo,
								APUserID: caPUserIDs.join(','),
								RoleIDs: croleIDs.join(','),
								JobLevel: Joblevel,
								ClassIDs: cclassIDs.join(','),
								SignedWay: signedWay,
								FlowType: flowType
							}, function() {});
							flowNo++;
							if (node.childNode) {
								saveApproveFunc(node.childNode, flowNo);
							}
						};

						saveApproveFunc(appConfigObj.nodeConfig.childNode, 1);

						setTimeout(() => {
							that.Request.requestByUrl("/Approve/BgApproval", {
								approveType: 0,
								tableName: that.globalData.physicalTableName,
								keyName: that.BaseScreenParm.keyName,
								keyId: that.BaseScreenParm.keyValue,
								APFlowID: APFlowID,
								userId: that.$store.state.UserInfo.UserID,
								title: that.processConfig.workFlowDef.name,
							}, function(approveRet) {

								uni.$m.utils.showLoading();

								if (approveRet.ds[0].status == "500") {
									uni.$m.utils.msg(approveRet.ds[0].msg)
								} else {
									uni.navigateBack({
										delta: 1,
										success() {
											that.eventChannel.emit('doneConfirm', 0);
										}
									})
								}

							})

						}, 1000)

					})


				} catch (e) {
					uni.$m.utils.showLoading();
					//TODO handle the exception
				}

			},
			closeFlowChart() { // 流程弹层取消按钮
				this.$refs.showFlowChart.close();
			},
			post(sql, param, callBack) {
				param["sql"] = sql;
				if (this.Request.getUserInfo()) {
					if (!param.hasOwnProperty("P_UserID")) {
						param.P_UserID = this.Request.getUserInfo().UserID;
					}
					if (!param.hasOwnProperty("P_UserName")) {
						param.P_UserName = this.Request.getUserInfo().UserName;
					}
					if (!param.hasOwnProperty("P_UserCode")) {
						param.P_UserCode = this.Request.getUserInfo().UserCode;
					}
				}
				this.Request.requestByUrl("/SQLData/QuerySql", param, function(data) {
					callBack(data);
				}, function(err) {
					console.log(err)
				});
			},
		}
	}
</script>

<style lang="scss">
	@import "/static/assets/css/nodeWarp/workflow.css";

	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}


	.error-modal-list {
		width: 455px;
	}

	.BottomBox {
		z-index: 9;
		position: fixed;
		bottom: 0;
		left: 0;
		height: 60px;
		width: 100vw;
		background-color: #fff;

		&-btnBox {
			height: 100%;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			.CommonBtnSize {
				padding: 10px 15px !important;
				margin-right: 8px;
			}
		}
	}
</style>